/*
 * #%L
 * SwiftUIWeb
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.linkwithweb.products.swiftui.context.ExcelFile;
import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dataobject.FrameworkUpload;

/**
 * @author ashwin
 *         Updated ON: Dec 17, 2012 10:32:34 AM
 * 
 */
@Controller
public class ModuleManager extends AbstractController {

	// Constants ----------------------------------------------------------------------------------

	private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.

	// Properties ---------------------------------------------------------------------------------

	private String filePath;

	// Actions ------------------------------------------------------------------------------------
	@RequestMapping("/module/load")
	public void loadModuleResource(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		// Get requested file by path info.
		String requestedFile = request.getParameter("fileName");
		String basePath = 	request.getSession().getServletContext().getRealPath("/");
		filePath = basePath + "/modules/test/"+SystemContext.getInstance().getUserContext().getFrameworkUser().getUserId()+"/";
		
		// Check if file is actually supplied to the request URI.
		if (requestedFile == null) {
			// Do your thing if the file is not supplied to the request URI.
			// Throw an exception, or send 404, or show default/warning page, or just ignore it.
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		// Decode the file name (might contain spaces and on) and prepare file object.
		File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

		// Check if file actually exists in filesystem.
		if (!file.exists()) {
			// Do your thing if the file appears to be non-existing.
			// Throw an exception, or send 404, or show default/warning page, or just ignore it.
			response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
			return;
		}

		// Get content type by filename.
		String contentType = getServletContext().getMimeType(file.getName());

		// If content type is unknown, then set the default value.
		// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
		// To add new content types, add new mime-mapping entry in web.xml.
		if (contentType == null) {
			contentType = "application/octet-stream";
		}

		// Init servlet response.
		response.reset();
		response.setBufferSize(DEFAULT_BUFFER_SIZE);
		response.setContentType(contentType);
		response.setHeader("Content-Length", String.valueOf(file.length()));
		//response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

		// Prepare streams.
		BufferedInputStream input = null;
		BufferedOutputStream output = null;

		try {
			// Open streams.
			input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
			output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

			// Write file contents to response.
			byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int length;
			while ((length = input.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// Gently close streams.
			close(output);
			close(input);
		}

	}

	// Actions ------------------------------------------------------------------------------------
	@RequestMapping("/module/upload")
	public void uploadModule(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		if (!(request instanceof org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest)) {
			return;
		}

		org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest multiPartRequest = (org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest) request;
		String uploadedFileName = ((org.springframework.web.multipart.commons.CommonsMultipartFile) (multiPartRequest.getFileMap().values()
				.toArray()[0])).getOriginalFilename();
		String fileKey = multiPartRequest.getFileMap().keySet().toArray(new String[0])[0];

		// Some type of file processing...
		System.err.println("-------------------------------------------");

		System.err.println("Uploading file: " + uploadedFileName);
		System.err.println("-------------------------------------------");
		String fileName = getUniqueString() + "_" + uploadedFileName;
		String basePath = "";
		try {
			File destinationDir = null;

			
			basePath = 	request.getSession().getServletContext().getRealPath("/");
			filePath = basePath + "/modules/test/"+SystemContext.getInstance().getUserContext().getFrameworkUser().getUserId()+"/";
			destinationDir = new File(filePath);

			if (!destinationDir.exists()) {
				destinationDir.mkdirs();
			}

			File file = new File(destinationDir, fileName);
			String path = file.getAbsolutePath();
			final String currentContextPath = request.getContextPath();
			// uploadbean.getFiledata().transferTo(file);

			multiPartRequest.getFile(fileKey).transferTo(file);

			com.linkwithweb.products.swiftui.utils.ZipUtil.extractZip(
					file.getAbsolutePath(), filePath);
			// file.delete();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}

	}

	// Helpers (can be refactored to public utility class) ----------------------------------------

	private static void close(Closeable resource) {
		if (resource != null) {
			try {
				resource.close();
			} catch (IOException e) {
				// Do your thing with the exception. Print it, log it or mail it.
				e.printStackTrace();
			}
		}
	}
}
